package com.xxx.controller;

import com.xxx.config.Request;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author George
 */
@Api("登录控制")
@CrossOrigin
@RestController
public class LoginController {

    @ApiOperation(value = "用户登录路径")
    @PostMapping("/login")
    public Request login(
            @RequestParam("workNumber") String workNumber,
            @RequestParam("password") String password) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(workNumber, password);

        try {
            subject.login(token);
            return Request.suc("欢迎使用");
        } catch (UnknownAccountException e) {
            return Request.error("用户名错误");
        } catch (IncorrectCredentialsException e) {
            return Request.error("密码错误");
        }
    }

    @ExceptionHandler(UnknownAccountException.class)
    public Request handleUnknownAccountException(UnknownAccountException e) {
        return Request.error("用户名错误");
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    public Request handleIncorrectCredentialsException(IncorrectCredentialsException e) {
        return Request.error("密码错误");
    }

}
